/*
 * 评测单词
 */

import * as React from 'react';
import { connect } from 'react-redux';
import { get } from 'lodash';

import { Tag, Divider, Spin, Icon, Tooltip, Card, message, Popconfirm } from 'antd';
import CustomPagination from 'components/common/CustomPagination';
import CustomModal from 'components/common/CustomModal';
import SearchForm from './SearchForm';
import EditForm from './EditForm';
import AudioPlayer from 'components/common/AudioPlayer';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/review';

import './Index.scss';

import { fetchWordList, createWord, updateWord, removeWord, fetchLevelList } from 'actions/review';

interface WordProps {
  dispatch: (action: any) => any;
  loadingGroup: any;
  wordTotal: number;
  words: object[];
  doSelect?: boolean;
  levels: any[];
}

interface WordState {
  editWord: any;
  selectedWords: object[];
}

class Index extends React.Component<WordProps, WordState> {
  pageInit: number;
  pageSizeInit: number;
  filters: any;

  static defaultProps: WordProps = {
    dispatch: () => {},
    loadingGroup: {},
    wordTotal: 0,
    words: [],
    doSelect: false,
    levels: [],
  };
  constructor(props: WordProps) {
    super(props);
    this.state = {
      editWord: null,
      selectedWords: [],
    };

    this.pageInit = 1;
    this.pageSizeInit = 20;
    this.filters = {
      page: this.pageInit,
      pageSize: this.pageSizeInit,
    };
  }

  componentDidMount() {
    this.handleFetchWordList();
    this.handleFetchLevels();
  }

  showModal = (editWord?: any) => {
    this.setState({
      editWord,
    });
  };

  hideModal = () => {
    this.setState({
      editWord: null,
    });
  };

  // 分页回调
  onPageChange = (page: number) => {
    this.handleFetchWordList({ page });
  };

  handleFetchLevels() {
    const { dispatch } = this.props;
    dispatch(
      fetchLevelList({
        page: 1,
        pageSize: 99,
      })
    );
  }

  /**
   * 查询Word列表
   */
  handleFetchWordList = (params: any = {}, isSearch: boolean = false) => {
    this.filters = { ...this.filters, ...params };
    if (isSearch) {
      this.filters.page = this.pageInit;
    }
    this.props.dispatch(fetchWordList(this.filters));
  };

  handleRemoveWord = (wordId: number) => {
    this.props.dispatch(removeWord(wordId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('单词删除成功');
        this.handleFetchWordList();
      }
    });
  };

  /**
   * 创建或更新标签
   */
  handleEditorSubmit = (data: Record<string, any>) => {
    const { loadingGroup } = this.props;
    const { editWord } = this.state;

    const loadingKey = editWord ? ACTIONS.UPDATE_WORD : ACTIONS.CREATE_WORD;

    if (isLoading(loadingGroup, loadingKey)) return;

    const action = editWord ? updateWord(editWord.id, data) : createWord(data);

    this.props.dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        const msg = editWord ? '修改成功' : '创建成功';
        message.success(msg);
        this.handleFetchWordList();
        this.hideModal();
      }
    });
  };

  handleCheckChange = (target: any, checked: boolean) => {
    const { dispatch, doSelect } = this.props;

    if (doSelect) {
    } else {
      this.setState({
        editWord: target,
      });
    }
  };

  render() {
    const { loadingGroup, words, wordTotal, levels } = this.props;
    const { editWord, selectedWords } = this.state;

    const loadingKey = editWord ? ACTIONS.UPDATE_WORD : ACTIONS.CREATE_WORD;

    const paginParams = {
      current: this.filters.page,
      pageSize: this.filters.pageSize,
      total: wordTotal,
      onChange: this.onPageChange,
    };

    const modalProps = {
      title: editWord ? '编辑单词' : '新增单词',
      visible: editWord !== null,
      onCancel: this.hideModal,
      footer: false,
    };

    return (
      <div id="word_content_box">
        <Card bordered={false}>
          <SearchForm
            levels={levels}
            showModal={this.showModal}
            handleSearch={this.handleFetchWordList}
          />
        </Card>
        <Card style={{ marginTop: 24, minHeight: 120 }}>
          <Spin spinning={isLoading(loadingGroup, ACTIONS.FETCH_WORD_LIST)} tip="Loading...">
            {words.length > 0 ? (
              words.map((word: any) => {
                const title = (
                  <Card>
                    {word.chinese}
                    <Divider type="vertical" key="line" />
                    L{word.level}
                  </Card>
                );
                return (
                  <Tooltip title={title} key={word.id}>
                    <Tag.CheckableTag
                      checked={selectedWords.some((item: any) => {
                        return item.id === word.id;
                      })}
                      onChange={(checked: boolean) => {
                        this.handleCheckChange(word, checked);
                      }}
                      key={word.id}>
                      {word.word}&nbsp;&nbsp;
                      <Popconfirm
                        placement="bottom"
                        title="确认要删除此单词吗？"
                        onConfirm={e => {
                          e.stopPropagation();
                          this.handleRemoveWord(word.id);
                        }}
                        onCancel={e => {
                          e.stopPropagation();
                        }}
                        okText="确认"
                        cancelText="取消">
                        <Icon
                          type="cross"
                          onClick={e => {
                            e.stopPropagation();
                          }}
                        />
                      </Popconfirm>
                    </Tag.CheckableTag>
                  </Tooltip>
                );
              })
            ) : (
              <p className="loading-placeholder">
                <Icon type="frown-o" />&nbsp; 还没有单词哦
              </p>
            )}
          </Spin>
        </Card>
        <CustomPagination {...paginParams} />
        <div className="clear-both" />
        <CustomModal {...modalProps}>
          <EditForm
            loading={isLoading(loadingGroup, loadingKey)}
            editWord={editWord}
            onSubmit={this.handleEditorSubmit}
            levels={levels}
          />
        </CustomModal>
      </div>
    );
  }
}

function mapStateToProps(state: any) {
  const { loadingGroup } = state;
  const { words, wordTotal, levels } = state.review;
  return {
    loadingGroup,
    words,
    wordTotal,
    levels,
  };
}

export default connect(mapStateToProps)(Index);
